package org.tpc.yn.utils;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JDBCUtil {

    public static boolean isOracle(Connection conn) throws SQLException {
        return  conn.getMetaData().getDatabaseProductName().toUpperCase().contains("ORACLE");
    }

    public static Map<String,String> getTableColumnType(Connection connection, String tableName) throws SQLException {
        DatabaseMetaData metadata = null;
        Map<String,String> map = new HashMap<>();
        try {
            metadata = connection.getMetaData();
            ResultSet resultSet =
                    metadata.getColumns(null, null, tableName.toUpperCase(), null);
            while (resultSet.next()) {
                String name = resultSet.getString("COLUMN_NAME").toLowerCase();
                String nameType = resultSet.getString("TYPE_NAME").toLowerCase();
                if(name.toUpperCase().equals("COMMENT")){
                    name = "\""+name + "\"";
                }
                map.put(name,nameType);
            }
            resultSet.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return map;
    }


    /**
     * 获取主键字段
     * @param connection
     * @param tableName
     * @return
     * @throws SQLException
     */
    public static List<String> getTableColumnPK(Connection connection, String tableName) throws SQLException {
        DatabaseMetaData metadata = null;
        List<String> list = new ArrayList<>();
        try {
            metadata = connection.getMetaData();
            ResultSet resultSet = metadata.getPrimaryKeys(null, null, tableName.toUpperCase());
            while (resultSet.next()) {
                String columnName = resultSet.getString("COLUMN_NAME");
                list.add(columnName);
            }
            resultSet.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
}
